package com.example.grpcserver;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;

import java.io.IOException;
import java.net.ServerSocket;

@SpringBootApplication
public class GrpcServerApplication implements ApplicationListener<ContextRefreshedEvent> {

    private static final Logger logger = LoggerFactory.getLogger(GrpcServerApplication.class);

    @Value("${grpc.server.port:9090}")
    private int grpcPort;

    public static void main(String[] args) {
        SpringApplication.run(GrpcServerApplication.class, args);
    }
    
    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
        logger.info("gRPC 服务器已启动，监听端口: {}", grpcPort);

        // 检查端口是否可用
        checkPortAvailability(grpcPort);
    }

    /**
     * 检查端口是否可用
     *
     * @param port 要检查的端口
     */
    private void checkPortAvailability(int port) {
        try {
            // 尝试绑定端口
            ServerSocket serverSocket = new ServerSocket(port);
            serverSocket.close();
            logger.error("警告：gRPC 端口 {} 似乎没有被应用程序使用！", port);
        } catch (IOException e) {
            // 端口被占用，这是我们期望的情况
            logger.info("gRPC 端口 {} 已被使用，这表明服务器可能已正确启动", port);
        }
    }
}